package com.mlnx.netty.app.ecg.handler;


import com.mlnx.common.utils.MyLog;
import com.mlnx.mptp.ResponseCode;
import com.mlnx.mptp.mptp.MpPacket;
import com.mlnx.mptp.mptp.body.Body;
import com.mlnx.mptp.mptp.head.Header;
import com.mlnx.netty.app.ecg.message.AbstractMessage;
import com.mlnx.netty.app.ecg.message.PublishMessage;
import com.mlnx.netty.app.ecg.message.RegisterMessage;
import com.mlnx.tp.base.model.DeviceType;

import org.apache.commons.lang3.StringUtils;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class MpServerHandle extends SimpleChannelInboundHandler<MpPacket> {

    private MyLog log = MyLog.getLog(getClass());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MpPacket mpPacket){

        Header header = mpPacket.getHeader();
        Body body = mpPacket.getBody();

        AbstractMessage message = null;
        MpPacket packet = null;

        switch (mpPacket.getHeader().getPacketType()) {
            case REGISTER:

                if (StringUtils.isEmpty(body.getDeviceId())) {
                    log.error("缺少  deviceID ");
                    packet = new MpPacket().registerAck(DeviceType.SERVER, ResponseCode.LACK_DEVICEID);
                    ctx.channel().writeAndFlush(packet);
                    break;
                }

                RegisterMessage registerMessage = new RegisterMessage();
                message = registerMessage;
                registerMessage.setDeviceId(body.getDeviceId());
                registerMessage.setKeepAliveTimer(body.getKeepAliveTimer());
                break;

            case PUBLISH:
                PublishMessage publishMessage = new PublishMessage();
                publishMessage.setBody(body);
                publishMessage.setQoS(header.getQoS());
                publishMessage.setDeviceType(header.getDeviceType());
                message = publishMessage;
                break;
            case PUBLISH_ACK:
                break;
            case PINGREQ:
                packet = new MpPacket().pong(DeviceType.SERVER);
                ctx.channel().writeAndFlush(packet);
                break;
            case PINGRESP:
                break;
            default:
        }

        if (message != null) {
            message.setDeviceType(header.getDeviceType());
            ctx.fireChannelRead(message);
        }
    }

}
